#include "StdAfx.h"
#include "ListenSocket.h"

CListenSocket::CListenSocket(void)
{
	listenSocket = INVALID_SOCKET;
}

CListenSocket::~CListenSocket(void)
{
	closesocket(listenSocket);
}

bool CListenSocket::Create(const char *szPort) {
	struct addrinfo *result = NULL;
    struct addrinfo hints;
	int iResult;

	ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;
	
	iResult = getaddrinfo(NULL, szPort, &hints, &result);
    if (iResult != 0) 
        return 0;

	listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (listenSocket == INVALID_SOCKET) {
        freeaddrinfo(result);
        return 0;
    }

	iResult = bind(listenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        freeaddrinfo(result);
        return 0;
    }

    freeaddrinfo(result);
	return 1;
}

void CListenSocket::Close() {
	closesocket(listenSocket);
}

bool CListenSocket::Listen(int nConnectionBacklog) {
	int iResult = listen(listenSocket, nConnectionBacklog);
    if (iResult == SOCKET_ERROR)
        return 0;
	return 1;
}

bool CListenSocket::Accept(CConnectSocket &connectSocket, sockaddr *addr, int *addrLen) {
	SOCKET sock = accept(listenSocket, addr, addrLen);
	if (sock == INVALID_SOCKET) 
        return 0;
	connectSocket.Create(&sock);
	return 1;
}

SOCKET& CListenSocket::GetSocket() {
	return listenSocket;
}

bool CListenSocket::isInvalidSocket() {
	return listenSocket == INVALID_SOCKET;
}